/*
 * Copyright 2010 Chad Retz
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package org.jdocng.parse.qdox;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.io.Reader;
import java.net.URL;

import org.jdocng.parse.ParseException;
import org.jdocng.parse.Parser;
import org.jdocng.parse.qdox.function.PackageFunction;
import org.jdocng.shared.Configuration;
import org.jdocng.shared.context.Context;
import org.jdocng.shared.model.Logger;

import com.thoughtworks.qdox.JavaDocBuilder;
import com.thoughtworks.qdox.model.JavaPackage;

/**
 * Parser using the <a href="http://qdox.codehaus.org">QDox library</a>
 * to parse and build javadoc
 * <p>
 * Not yet implemented
 *
 * @author Chad Retz
 */
public class QDoxParser implements Parser {

    private final JavaDocBuilder builder = new JavaDocBuilder();
    
    @Override
    public String getShortName() {
        return "QDox";
    }
    
    @Override
    public void addSource(File file) throws IOException {
        builder.addSource(file);
    }

    @Override
    public void addSource(Reader reader) {
        builder.addSource(reader);
    }

    @Override
    public void addSource(URL url) throws IOException {
        builder.addSource(url);
    }
    
    @Override
    public void addDirectory(File directory) throws IOException {
        addDirectory(directory, new FileFilter() {
            @Override
            public boolean accept(File pathname) {
                return pathname.getName().endsWith(".java");
            }
        });
    }

    @Override
    public void addDirectory(File directory, FileFilter filter) throws IOException {
        //doing this myself, cuz qdox doesn't have filtering at this level
        if (directory.exists() && directory.isDirectory()) {
            for (File file : directory.listFiles(filter)) {
                addSource(file);
            }
        }
    }

    @Override
    public Context parse(Configuration configuration, Logger logger)
            throws ParseException {
        QDoxContext context = new QDoxContext(builder);
        context.setConfiguration(configuration);
        context.setLogger(logger);
        for (JavaPackage pkg : builder.getPackages()) {
            PackageFunction.getInstance().apply(context, pkg);
        }
        return context;
    }
}
